import fs from 'fs' //  文件相关操作工具库
import path from 'path' //  本地库 路径
import { fileURLToPath } from 'url'
import getSettingJson from './getSettingJson.js'
const settingJson = getSettingJson()

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

export default function writeSettingJson(sourcePath, reset = false) {
  // 修改对象
  if (sourcePath) settingJson.source = sourcePath
  if (reset) settingJson.source = settingJson.defaultSource
  // 将修改后的对象转换为 JSON 字符串
  const updatedData = JSON.stringify(settingJson, null, 2)
  const filePath = path.join(__dirname, '../setting.json')
  return new Promise((resolve, reject) => {
    // 写回 JSON 文件
    fs.writeFile(filePath, updatedData, 'utf-8', writeErr => {
      if (writeErr) {
        reject('Error writing file:', writeErr)
        return
      }
      resolve('File updated successfully.')
    })
  })
}
